package com.cm.common.utils;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.exception.CosClientException;
import com.qcloud.cos.exception.CosServiceException;
import com.qcloud.cos.model.*;
import com.qcloud.cos.region.Region;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

/**
 * @类 名：COSStorage </br>
 * @描 述：</br>
 * @日 期：2020/9/29 17:36</br>
 * @作 者：常明</br>
 * @版 本：1.0.0
 * @since JDK 1.8
 */
public class COSStorage {
    // 1 初始化用户身份信息（secretId, secretKey）。
    private static String secretId = "AKIDzmKeiUlFGTt291sy2KPEqofNozxiERec";
    private static String secretKey = "sUq01mGBuIQKFxOkqjOnBLDo7BzWmUyC";
    private static COSClient cosClient=null;

    static {
        COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
        // 2 设置 bucket 的区域, COS 地域的简称请参照 https://cloud.tencent.com/document/product/436/6224
        // clientConfig 中包含了设置 region, https(默认 http), 超时, 代理等 set 方法, 使用可参见源码或者常见问题 Java SDK 部分。
        Region region = new Region("ap-beijing");
        ClientConfig clientConfig = new ClientConfig(region);
        // 3 生成 cos 客户端。
        cosClient = new COSClient(cred, clientConfig);
    }
    public static String upload(String path){
        // 指定要上传的文件
        File localFile = new File(path);
        // 指定要上传到的存储桶
        String bucketName = "team-shop-1303824460";
        // 指定要上传到 COS 上对象键
        Date date=new Date();
        String key = "/shop-images/"+date.getTime()+".jpg";
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, localFile);
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        return ( "https://" + bucketName + ".cos." + "ap-beijing"+ ".myqcloud.com" + key);
    }
    public String upload(InputStream inputStream, String ext) throws IOException {
        // 指定要上传到的存储桶
        String bucketName = "team-shop-1303824460";
        // 指定要上传到 COS 上对象键
        Date date = new Date();
        String key = "/shop-images/"+date.getTime()+".jpg";
        // 元数据
        ObjectMetadata objectMetadata = new ObjectMetadata();
        // 设置 Content type, 默认是 application/octet-stream
        objectMetadata.setContentType("image/"+ext);
        // 请求对象
        PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key, inputStream, objectMetadata);
        // 请求
        PutObjectResult putObjectResult = cosClient.putObject(putObjectRequest);
        putObjectRequest.setTrafficLimit(200*1024*1024);
        return ( "https://" + bucketName + ".cos." + "ap-beijing"+ ".myqcloud.com" + key);
    }
    public static boolean delete(String key){
        // Bucket的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        String bucketName = "team-shop-1303824460";
        cosClient.deleteObject(bucketName, key);
        return true;
    }
    public static void getList(){
        // Bucket的命名格式为 BucketName-APPID ，此处填写的存储桶名称必须为此格式
        String bucketName = "team-shop-1303824460";
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest();
        // 设置bucket名称
        listObjectsRequest.setBucketName(bucketName);
        // prefix表示列出的object的key以prefix开始
        listObjectsRequest.setPrefix("/shop-images/");
        // deliter表示分隔符, 设置为/表示列出当前目录下的object, 设置为空表示列出所有的object
        listObjectsRequest.setDelimiter("/");
        // 设置最大遍历出多少个对象, 一次listobject最大支持1000
        listObjectsRequest.setMaxKeys(1000);
        ObjectListing objectListing = null;
        do {
            try {
                objectListing = cosClient.listObjects(listObjectsRequest);
            } catch (CosServiceException e) {
                e.printStackTrace();
                return;
            } catch (CosClientException e) {
                e.printStackTrace();
                return;
            }
            // common prefix表示表示被delimiter截断的路径, 如delimter设置为/, common prefix则表示所有子目录的路径
            List<String> commonPrefixs = objectListing.getCommonPrefixes();

            // object summary表示所有列出的object列表
            List<COSObjectSummary> cosObjectSummaries = objectListing.getObjectSummaries();
            for (COSObjectSummary cosObjectSummary : cosObjectSummaries) {
                // 文件的路径key
                String key = cosObjectSummary.getKey();
                System.out.println(key);
                // 文件的etag
                String etag = cosObjectSummary.getETag();
                // 文件的长度
                long fileSize = cosObjectSummary.getSize();
                // 文件的存储类型
                String storageClasses = cosObjectSummary.getStorageClass();
            }

            String nextMarker = objectListing.getNextMarker();
            listObjectsRequest.setMarker(nextMarker);
        } while (objectListing.isTruncated());
    }
}
